Ext.namespace("Farm");

Farm.DiscountProductsSelectWindow = function(pPanel){
	this.pPanel = pPanel;
	this.productsStore = new Ext.data.JsonStore({
		autoLoad: true,
		url: "/typo3/ajax.php",
		root: "products",
		baseParams: {
			ajaxID: "FarmDiscounts::getProducts",
			article: "",
			title: "",
			manufacturer: "",
			country: "",
			category: ""
		},
		fields: ["uid", "article", "title", "category"],
		id: "uid",
		totalProperty: "totalRecords",
		remoteSort: true,
		sortInfo: {field: "article", direction: "ASC"}
	});

	Farm.DiscountProductsPanel.superclass.constructor.call(this, {
		modal: true,
		title: "Товары",
		width: 600,
		height: 520,
		buttons: [{
			id: "discountProductAddButton",
			text: "Добавить",
			disabled: true,
			handler: this.selectProduct,
			scope: this
		}, {
			text: "Отмена",
			handler: this.close,
			scope: this
		}],
		items: [{
			xtype: "form",
			region: "north",
			autoHeight: true,
			bodyStyle: "padding: 5px; background-color: #f0f0f0",
			border: false,
			buttonAlign: "right",
			items: [{
				xtype: "fieldset",
				title: "Поиск",
				autoHeight: true,
				items: [{
					id: "discountProductsSearchArticleField",
					xtype: "textfield",
					fieldLabel: "Артикул",
					layout: "form",
					anchor: "100%",
					enableKeyEvents: true,
					listeners: {
						keyup: this.searchFieldOnKeyUp,
						scope: this
					}
				},{
					id: "discountProductsSearchTitleField",
					xtype: "textfield",
					fieldLabel: "Название",
					anchor: "100%",
					enableKeyEvents: true,
					listeners: {
						keyup: this.searchFieldOnKeyUp,
						scope: this
					}
				}, {
					id: "discountProductsSearchManufacturerField",
					xtype: "combo",
					fieldLabel: "Производитель",
					anchor: "100%",
					forceSelection: true,
					lazyInit: true,
					displayField: "title",
					valueField: "uid",
					minChars: 1,
					triggerAction: "all",
					store: new Ext.data.JsonStore({
						url: "/typo3/ajax.php",
						baseParams: {
							ajaxID: "FarmDiscounts::getManufacturers"
						},
						fields: ["uid", "title"],
						root: "manufacturers"
					})
				}, {
					id: "discountProductsSearchCoutryField",
					xtype: "combo",
					fieldLabel: "Страна",
					anchor: "100%",
					forceSelection: true,
					lazyInit: true,
					displayField: "title",
					valueField: "uid",
					minChars: 1,
					triggerAction: "all",
					store: new Ext.data.JsonStore({
						url: "/typo3/ajax.php",
						baseParams: {
							ajaxID: "FarmDiscounts::getCountries"
						},
						fields: ["uid", "title"],
						root: "countries"
					})
				}, {
					id: "discountProductsSearchCategoryField",
					xtype: "combo",
					fieldLabel: "Категория",
					anchor: "100%",
					forceSelection: true,
					lazyInit: true,
					displayField: "title",
					valueField: "uid",
					minChars: 1,
					triggerAction: "all",
					store: new Ext.data.JsonStore({
						url: "/typo3/ajax.php",
						baseParams: {
							ajaxID: "FarmDiscounts::getCategoriesCombo"
						},
						fields: ["uid", "title"],
						root: "categories"
					})
				}]
			}],
			buttons: [{
				text: "Искать",
				handler: this.updateFilter,
				scope: this
			}, {
				text: "Очистить",
				handler: this.clearFilter,
				scope: this
			}]
		}, {
			id: "discountProductsSearchGrid",
			xtype: "grid",
			region: "center",
			store: this.productsStore,
			autoExpandColumn: "title",
			enableHdMenu: false,
			columns: [{
					id: "article",
					header: "Артикул",
					dataIndex: "article",
					sortable: true,
					width: 70
				}, {
					id: "title",
					header: "Название",
					dataIndex: "title",
					sortable: true
				}, {
					id: "category",
					header: "Категория",
					dataIndex: "category",
					sortable: true,
					width: 120
				}
			],
			viewConfig: {forceFit: true},
			sm: new Ext.grid.RowSelectionModel({
				singleSelect: true,
				listeners: {
					selectionchange: function(sModel) {
						if (sModel.getCount() > 0) {
							Ext.getCmp("discountProductAddButton").enable();
						} else {
							Ext.getCmp("discountProductAddButton").disable();
						}
					}
				}
			}),
			bbar: new Ext.PagingToolbar({
				store: this.productsStore,
				displayInfo: true
			}),
			listeners: {
				rowdblclick: this.selectProduct,
				scope: this
			}
		}],
		layout: "border"
	});
	this.doLayout();
}
Ext.extend(Farm.DiscountProductsSelectWindow, Ext.Window, {
	updateFilter: function() {
		this.productsStore.baseParams.article = Ext.getCmp("discountProductsSearchArticleField").getValue();
		this.productsStore.baseParams.title = Ext.getCmp("discountProductsSearchTitleField").getValue();
		this.productsStore.baseParams.manufacturer = Ext.getCmp("discountProductsSearchManufacturerField").getValue();
		this.productsStore.baseParams.country = Ext.getCmp("discountProductsSearchCoutryField").getValue();
		this.productsStore.baseParams.category = Ext.getCmp("discountProductsSearchCategoryField").getValue();
		this.productsStore.reload();
	},
	clearFilter: function() {
		Ext.getCmp("discountProductsSearchArticleField").reset();
		Ext.getCmp("discountProductsSearchTitleField").reset();
		Ext.getCmp("discountProductsSearchManufacturerField").reset();
		Ext.getCmp("discountProductsSearchCoutryField").reset();
		Ext.getCmp("discountProductsSearchCategoryField").reset();
		
		this.productsStore.baseParams.article = "";
		this.productsStore.baseParams.title = "";
		this.productsStore.baseParams.manufacturer = "";
		this.productsStore.baseParams.country = "";
		this.productsStore.baseParams.category = "";
		this.productsStore.reload();
	},
	selectProduct: function() {
		var mGrid = Ext.getCmp("discountProductsSearchGrid");
		if (mGrid.getSelectionModel().getCount() > 0) {
			var sProduct = mGrid.getSelectionModel().getSelected();
			this.pPanel.addProduct(sProduct.get("uid"), sProduct.get("article"), sProduct.get("title"));
			this.close();
		}
	},
	searchFieldOnKeyUp: function(field, e) {
		if (e.getKey() == Ext.EventObject.ENTER) {
			this.updateFilter();
		}
	}
});

Farm.DiscountProductsPanel = function(config){
	this.pProductsStore = new Ext.data.JsonStore({
		fields: [
			{name: "id"},
			{name: "article"},
			{name: "title"}
		],
		autoLoad: true,
		data: config.selectedProducts,
		id: 0
	});
	this.uid = config.uid;
	
	Farm.DiscountProductsPanel.superclass.constructor.call(this, {
		applyTo: Ext.get("data[user_farm_commerce_discounts][" + config.uid + "][products_control]"),
		width: 528,
		height: 300,
		viewConfig: {
			forceFit: true,
			emptyText: "Нет записей"
		},
		columns: [{
			id: "article",
			header: "Артикул",
			dataIndex: "article",
			sortable: false,
			width: 70
		}, {
			id: "title",
			header: "Название",
			dataIndex: "title",
			sortable: false,
			css: "discount-product"
		}],
		autoExpandColumn: "title",
		enableHdMenu: false,
		sm: new Ext.grid.RowSelectionModel({
			singleSelect: true,
			listeners: {
				selectionchange: function(sModel) {
					if (sModel.getCount() > 0) {
						Ext.getCmp("discountProductsRemoveButton").enable();
					} else {
						Ext.getCmp("discountProductsRemoveButton").disable();
					}
				}
			}
		}),
		store: this.pProductsStore,
		tbar: [{
			iconCls: "add-discount-product",
			text: "Добавить",
			handler: this.showSelectWindow,
			scope: this
		}, {
			id: "discountProductsRemoveButton",
			iconCls: "remove-discount-product",
			text: "Удалить",
			disabled: true,
			handler: this.removeProduct,
			scope: this
		}]
	});
}
Ext.extend(Farm.DiscountProductsPanel, Ext.grid.GridPanel, {
	addProduct: function(id, article, title){
		var ProductRecord = Ext.data.Record.create([
			{name: "id"},
			{name: "article"},
			{name: "title"}
		]);
		var sProduct = new ProductRecord({
			id: id,
			article: article,
			title: title
		});
		this.pProductsStore.add(sProduct);
		this.saveChanges();
	},
	removeProduct: function(){
		if (this.getSelectionModel().getCount() > 0) {
			this.pProductsStore.remove(this.getSelectionModel().getSelected());
			this.saveChanges();
		}
	},
	saveChanges: function(){
		var sProducts = this.pProductsStore.collect("id", false, true);
		Ext.get("data[user_farm_commerce_discounts][" + this.uid + "][products]").dom.value = sProducts.toString();
	},
	showSelectWindow: function(){
		var sWindow = new Farm.DiscountProductsSelectWindow(this);
		sWindow.show();
	}
});